<template>
	<view class="wrap">
		<u--form
				labelPosition="left"
				:model="postModel"
				ref="newPostForm"
				data-pageNum="0"
		>
			<!-- 缩略图 -->
			<u-form-item
				:borderBottom="false"
				ref="item1"
				labelWidth="1"
			>				
				<u-upload
					:fileList="fileList1"
					@afterRead="afterRead"
					@delete="deletePic"
					uploadText="上传配图"
					name="1"
					multiple
					:maxCount="9"
				></u-upload>
				
			</u-form-item>
			
			<!-- 标题 -->
			<u-form-item
				prop="postInfo.title"
				borderBottom
				ref="item2"
			>
				<u--input
					v-model="postModel.postInfo.title"
					border="none"
					placeholder="填写标题会有更多赞哦~"
				></u--input>
			</u-form-item>			
			
			<!-- 正文 -->
			<u-form-item
				prop="postInfo.body"
				:border="false"
				ref="item3"
				labelWidth="1"
			>
				<u--textarea
					placeholder="瞬间内容不少于1个字"
					v-model="postModel.postInfo.body"
					border="none"
					height="150"
					maxlength="1000"
					value
					count
				></u--textarea>
			</u-form-item>
			
			<!-- <view class="tag_box">
				<text>#话题</text>
				<text>@用户</text>				
			</view> -->
			
			<view style="padding: 12px 0;">
				<u-line></u-line>
			</view>
			
			<view class="cflex">
				<view class="dflex jcsb" @click="chooseLocation">
					<view class="dflex">
						<u-icon name="map" color="#333"></u-icon>
						<text class="f14 ml5">{{ chooseLocationText }}</text> 
					</view>
					<u-icon name="arrow-right" color="#ccc"></u-icon>
				</view>
				<text class="f12 mt5 ca3a3a3">{{ location_detail }}</text>
				<!-- <u-scroll-list :indicator="indicator">
					 <view class="location_tag">
						 <text class="u-line-1">爱情海购物广场123123213</text>
						 <text class="u-line-1">123</text>
						 <text class="u-line-1">东二环</text>
						 <text class="u-line-1">爱情海购物广场</text>
						 <text class="u-line-1">爱情海购物广场</text>
						 <text class="u-line-1">爱情海购物广场</text>
					</view>					
				</u-scroll-list> -->
			</view>
			
			<view class="mt12">
				<u-line></u-line>
			</view>
			
			<view class="cflex mt12">
				<view class="dflex jcsb" @click="chooseGoods">
					<view class="dflex">
						<u-icon name="shopping-cart" color="#333"></u-icon>
						<text class="f14 ml5">{{ merchantName }}</text> 
					</view>
					<u-icon name="arrow-right" color="#ccc"></u-icon>
				</view>
			</view>
			
			<view class="post_button">
				<!-- <view class="save_draft dflex jcc aic">
					<u-icon name="download" color="#333"></u-icon>
					<text class="ml5">保存草稿</text>
				</view> -->
				<view class="submit_post dflex jcc aic" @tap="$u.throttle(postEditTopic, 3000)">
					<u-icon name="checkbox-mark" color="#333"></u-icon>
					<text class="ml5">保存编辑</text>
				</view>
			</view>
			
		</u--form>		
		
		<u-toast ref="uToast"></u-toast>
		
	</view>
</template>

<script>
	
	
	export default {
		data() {
			return {
				postModel : {
					postInfo : {
						title : '',
						body : ''
					}
				},
				indicator: false,			
				fileList1: [],
				fileArray1: [],
				loginCheck:false,
				latitude : '',
				longitude : '',
				chooseLocationText : '获取定位',
				openLocationText : '导航',
				location_detail : '',
				location_name : '',
				login_type : '',
				delete_topic_id : '',
				merchantName:'关联商户',
				merchantId:'',
				topic_id : ''
			}
		},
		onReady:function(){
			this.user_check()
			if(uni.getStorageSync("login_type")) {
				this.login_type = true
			}
		},
		onLoad:function(e){			
			// this.topic_id = 806
			// console.log('eeeeeeeeee', e.TopicId)
			if(e.TopicId == undefined) {
				uni.redirectTo({
					url:'/pages/index/index'
				})
			} else {
				this.topic_id = e.TopicId
				uni.showLoading({
					title:"加载中...."
				})
				uni.request({
					url:uni.getStorageSync('domain') + '/api/v1/topic_edit/' + this.topic_id,
					method:'get',
					header: {
						'Accept': 'application/json',
						'Authorization' : 'Bearer ' + uni.getStorageSync('access_member_info').access_token
					},
					success: (res) => {
						this.fileList1 = JSON.parse(res.data.images).map(i => ({ url: i }));
						//默认图片地址，不然用户啥都不改，上传以后图片就丢了
						this.fileArray1 = JSON.parse(res.data.images);
						this.postModel.postInfo.title = res.data.title
						this.postModel.postInfo.body = (res.data.body).replace(new RegExp("<br />", "gm"), "\n"),
						this.delete_topic_id = res.data.id
						if(res.data.location_detail != "" && res.data.location_detail != null) {
							this.location_detail = res.data.location_detail
							this.chooseLocationText = res.data.location_name
							this.latitude = res.data.latitude
							this.longitude = res.data.longitude
						} 
						if(res.data.merchant_name != "" && res.data.merchant_name != null) {
							console.log('res.data.merchantName', res.data.merchant_name)
							this.merchantName = res.data.merchant_name,
							this.merchantId = res.data.merchant_id
						} 
						console.log(res)
						uni.hideLoading()
					},
					fail: (res) => {
					}
				})
			}
		},
		methods: {
			chooseGoods() {
				uni.navigateTo({
					url:'/packageShop/merchant/merchantSelect'
				})
			},
			refreshGoods(merchantName, merchantId) {
				this.merchantName = merchantName
				this.merchantId = merchantId
			},
			show_toast(mes) {
				this.$refs.uToast.show({
					message : mes,
				})
			},
			user_check(e) {
				uni.showLoading({
					title:"加载中...."
				})
				uni.request({
					url:uni.getStorageSync('domain') + '/api/v1/user',
					method:'get',
					header: {
						'Accept': 'application/json',
						'Authorization' : 'Bearer ' + uni.getStorageSync('access_member_info').access_token
					},
					success: (res) => {						
						if(res.statusCode == 401) {
							this.loginCheck = false
							uni.removeStorageSync('access_member_info')
							uni.navigateTo({
								url: '/pages/register/register'
							})
						}
						if(res.statusCode == 200 || res.statusCode == 201) {
							this.loginCheck = true
						}
						uni.hideLoading();
					},
					fail: (res) => {
					}
				})
			},
			deletePic(event) {
				this[`fileList${event.name}`].splice(event.index, 1)
				this[`fileArray${event.name}`].splice(event.index, 1)
				console.log(this[`fileArray${event.name}`])
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = [].concat(event.file)
				let fileListLen = this[`fileList${event.name}`].length
				lists.map((item) => {
					this[`fileList${event.name}`].push({
						...item,
						status: 'uploading',
						message: '上传中'
					})
				})
				for (let i = 0; i < lists.length; i++) {
					const result = await this.uploadFilePromise(lists[i].url)
					let item = this[`fileList${event.name}`][fileListLen]
					this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
						status: 'success',
						message: '',
						url: result
					}))
					fileListLen++
				}
			},
			uploadFilePromise(url) {
				console.log('请求接口');
				return new Promise((resolve, reject) => {
					let a = uni.uploadFile({
					url:uni.getStorageSync('domain') + '/api/v1/topic/topic_images',
						filePath: url,
						header: {
							'Authorization' : 'Bearer ' + uni.getStorageSync('access_member_info').access_token,
						},
						name: 'topicImages',
						formData: {
							'type'	:	'topic_image',
							'width'	:	1080
						},
						success: (res) => {							
							if(res.statusCode == 401) {
								// console.log('res', res.statusCode);
								uni.removeStorageSync('access_member_info');
								uni.navigateTo({
									url: '/pages/register/register'
								})
							} else {
								var images_path = JSON.parse(res.data).images;	
								this.fileArray1.push(images_path);	
								// console.log('array', this.fileArray1);
								setTimeout(() => {
									resolve(res.data.data)
								}, 1000)
							}
						},
						fail: (err) => {
							console.log(err);
						}
					});
				})
			},
			//保存编辑后的话题
			postEditTopic() {
				var body = this.postModel.postInfo.body;
				var image = this.fileArray1;
				console.log("编辑流程开始1111...", body.length)
				if(body.length < 1) {
					uni.$u.toast('瞬间内容不得少于1个字符');
					return;
				}
				if(image.length < 1) {
					uni.$u.toast('至少上传1张配图');
					return;
				}
				if(this.merchantName != '关联商户' && this.chooseLocationText == '获取定位') {
					uni.$u.toast('关联商户必须输入定位');
					return;
				}
				uni.showLoading({
					title: '保存中...',
					mask: true
				});
						
				uni.request({
					url:uni.getStorageSync('domain') + '/api/v1/topic_edit_save/' + this.topic_id,
					method:'POST',
					header: {
						'Accept': 'application/json',
						'Authorization' : 'Bearer ' + uni.getStorageSync('access_member_info').access_token
					},
					data: {
						'title' : this.postModel.postInfo.title,
						'body' : (this.postModel.postInfo.body).replace(new RegExp("\n", "gm"), "<br>"),
						'images' : this.fileArray1,
						'cover' : this.fileArray1[0],
						'latitude' : this.latitude,
						'longitude' : this.longitude,
						'location_detail' : this.location_detail,
						'location_name' : this.chooseLocationText,
						'delete_topic_id' : this.delete_topic_id,
						'merchant_name' : this.merchantName,
						'merchant_id' : this.merchantId
					},
					success: (res) => {
						// console.log(res.data.message);
						if(res.statusCode != 201) {
							this.show_toast(res.data.message);
						}
						if(res.data.status == 'success') {
							if(this.login_type) {
								this.show_toast('编辑成功');
							}
							setTimeout(function(){
								uni.redirectTo({
									url:"/pages/article/article2?TopicId=" + res.data.post_id
								})
							},1000)
						}
						uni.hideLoading();
					},
					fail: (res) => {
					}
				})	
				
			},
			chooseLocation() {
				uni.chooseLocation({
					type: 'gcj02',
					success: (res) => {
						// console.log('位置名称：' + res.name);
						// console.log('详细地址：' + res.address);
						// console.log('纬度：' + res.latitude);
						// console.log('经度：' + res.longitude);
						this.latitude = res.latitude;
						this.longitude = res.longitude;
						this.chooseLocationText = res.name;
						this.location_detail = res.address;
						this.location_name = res.name;
					},
					fail: (res) => {
						console.log(res)
					}
				});			
			}
		}
	}
</script>

<style>	
	page {
		background-color: #fff;
	}
	.tag_box {
		display: flex;
	}
	.tag_box text {
		background-color: #F6F6F6;
		color: #333;
		font-size: 14px;
		padding: 2px 5px;
		margin-right: 10px;
		border-radius: 5px;
	}
	.post_button {
		display: flex;
		color: #333;
		justify-content: space-between;
		position: absolute;
		bottom: 35px;
		width: 95%;
	}
	.save_draft {
		width: 29%;
		height: 50px;
		line-height: 50px;
		text-align: center;
		background-color: #EEEEEE;
		border-radius: 30px;
	}
	.submit_post {
		width: 100%;
		height: 50px;
		line-height: 50px;
		text-align: center;
		background-color: #FFD84A;
		border-radius: 30px;
	}
	.location_tag {
		margin-top: 5px;
		display: -webkit-inline-box;
	}
	.location_tag text {
		padding: 3px 7px;
		height: 16px;
		max-width: 110px;
		text-align: center;
		color: #666;
		border: 1px solid #ccc;
		border-radius: 30px;
		font-size: 12px;
		margin: 7px 7px 0 0;
	}
</style>
